import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { UploadTask } from '@/types'

export const useUploadStore = defineStore('upload', () => {
  const uploadTasks = ref<UploadTask[]>([])
  const isUploading = ref(false)

  // 添加上传任务
  const addUploadTask = (task: UploadTask) => {
    uploadTasks.value.push(task)
  }

  // 移除上传任务
  const removeUploadTask = (id: string) => {
    const index = uploadTasks.value.findIndex(task => task.id === id)
    if (index > -1) {
      uploadTasks.value.splice(index, 1)
    }
  }

  // 更新任务状态
  const updateTaskStatus = (id: string, status: UploadTask['status'], progress?: number, error?: string) => {
    const task = uploadTasks.value.find(t => t.id === id)
    if (task) {
      task.status = status
      if (progress !== undefined) {
        task.progress = progress
      }
      if (error) {
        task.error = error
      }
    }
  }

  // 清除已完成的任务
  const clearCompleted = () => {
    uploadTasks.value = uploadTasks.value.filter(task => 
      task.status !== 'completed' && task.status !== 'error'
    )
  }

  // 清空所有任务
  const clearAll = () => {
    uploadTasks.value = []
  }

  // 重试任务
  const retryTask = (id: string) => {
    const task = uploadTasks.value.find(t => t.id === id)
    if (task) {
      task.status = 'waiting'
      task.progress = 0
      task.error = undefined
    }
  }

  // 模拟上传进度
  const simulateUpload = (task: UploadTask): Promise<void> => {
    return new Promise((resolve, reject) => {
      task.status = 'uploading'
      
      const interval = setInterval(() => {
        task.progress += Math.random() * 15 + 5
        
        if (task.progress >= 100) {
          task.progress = 100
          task.status = 'processing'
          clearInterval(interval)
          
          // 模拟处理时间
          setTimeout(() => {
            if (Math.random() > 0.1) { // 90% 成功率
              task.status = 'completed'
              resolve()
            } else {
              task.status = 'error'
              task.error = '上传失败'
              reject(new Error('上传失败'))
            }
          }, 1500)
        }
      }, 300)
    })
  }

  // 开始上传
  const startUpload = async () => {
    const waitingTasks = uploadTasks.value.filter(task => task.status === 'waiting')
    if (waitingTasks.length === 0) return

    isUploading.value = true

    try {
      // 并发上传
      const promises = waitingTasks.map(task => simulateUpload(task))
      await Promise.allSettled(promises)
    } finally {
      isUploading.value = false
    }
  }

  return {
    uploadTasks,
    isUploading,
    addUploadTask,
    removeUploadTask,
    updateTaskStatus,
    clearCompleted,
    clearAll,
    retryTask,
    startUpload
  }
}) 